// lib/views/stock_list/stock_code_listItem.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/stock_list_controller.dart';

import '../../../data/models/recent_closing_price_model.dart';
import '../../../data/datasource/local/database.dart';

class StockCodeListItem extends StatefulWidget {
  final StockCode stockCode;

  const StockCodeListItem({super.key, required this.stockCode});

  @override
  State<StockCodeListItem> createState() => _StockCodeListItemState();
}

class _StockCodeListItemState extends State<StockCodeListItem> {
  bool _isExpanded = false;
  bool _isLoadingIndicators = false;
  final StockListController controller = Get.find<StockListController>();
  final GlobalKey _itemKey = GlobalKey(); // 每个列表项有自己的GlobalKey

  // 添加重试相关变量
  int _retryCount = 0;
  static const int _maxRetries = 3;
  bool _isLoadingRecentPrices = false;

  @override
  void initState() {
    super.initState();
    // 注册列表项的GlobalKey到控制器
    if (!controller.isControllerClosed) {
      controller.registerItemKey(widget.stockCode.symbol, _itemKey);
    }

    // 如果近期收盘价数据为空，尝试获取
    if (controller.getRecentPrices(widget.stockCode.symbol).isEmpty) {
      _loadRecentPricesWithRetry();
    }
  }

  @override
  void dispose() {
    // 取消注册列表项的GlobalKey
    if (!controller.isControllerClosed) {
      controller.unregisterItemKey(widget.stockCode.symbol);
    }
    super.dispose();
  }

  // 加载近期收盘价（带重试机制）
  Future<void> _loadRecentPricesWithRetry() async {
    if (_isLoadingRecentPrices ||
        _retryCount >= _maxRetries ||
        controller.isControllerClosed)
      return;

    setState(() {
      _isLoadingRecentPrices = true;
    });

    try {
      await controller.fetchRecentClosingPrices(widget.stockCode.symbol);

      // 检查是否获取到了数据
      final recentPrices = controller.getRecentPrices(widget.stockCode.symbol);
      if (recentPrices.isEmpty) {
        // 如果没有获取到数据，增加重试计数并稍后重试
        _retryCount++;
        if (_retryCount < _maxRetries) {
          Future.delayed(const Duration(seconds: 1), () {
            if (mounted && !controller.isControllerClosed) {
              _loadRecentPricesWithRetry();
            }
          });
        }
      }
    } catch (e) {
      print('加载近期收盘价失败: ${widget.stockCode.symbol}, $e');
      // 增加重试计数并稍后重试
      _retryCount++;
      if (_retryCount < _maxRetries) {
        Future.delayed(const Duration(seconds: 1), () {
          if (mounted && !controller.isControllerClosed) {
            _loadRecentPricesWithRetry();
          }
        });
      }
    } finally {
      if (mounted && !controller.isControllerClosed) {
        setState(() {
          _isLoadingRecentPrices = false;
        });
      }
    }
  }

  // 手动加载近期收盘价
  Future<void> _manualLoadRecentPrices() async {
    if (controller.isControllerClosed) return;

    setState(() {
      _retryCount = 0; // 重置重试计数
    });
    await _loadRecentPricesWithRetry();
  }

  // 计算四天前收盘价与当前价格的涨跌幅
  double _calculateFourDayChangePercent() {
    if (controller.isControllerClosed) return 0.0;

    final recentPrices = controller.getRecentPrices(widget.stockCode.symbol);
    final stockModel = controller.stockData[widget.stockCode.symbol];

    // 确保有足够的数据和当前价格
    if (recentPrices.length >= 4 &&
        stockModel != null &&
        stockModel.currentPrice > 0) {
      final fourthDayPrice = recentPrices[3].close;
      if (fourthDayPrice > 0) {
        return ((stockModel.currentPrice - fourthDayPrice) / fourthDayPrice) *
            100;
      }
    }

    return 0.0;
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      key: _itemKey, // 使用自己的GlobalKey
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: InkWell(
        onTap: () {
          if (controller.isControllerClosed) return;
          final stockModel = controller.stockData[widget.stockCode.symbol];
          controller.clickLookStock(
            widget.stockCode.symbol.replaceAll('.', ''),
          );
        },
        child: Column(
          children: [
            // 主要信息区域
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 股票名称、代码和价格区域
                  Row(
                    children: [
                      // 股票名称和代码
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text(
                                  widget.stockCode.name ??
                                      widget.stockCode.symbol,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 6,
                                    vertical: 2,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.grey[200],
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: Text(
                                    widget.stockCode.symbol,
                                    style: const TextStyle(fontSize: 12),
                                  ),
                                ),
                                const SizedBox(width: 8),
                                // 持仓标记 - 使用StockListController中的持仓数据
                                Obx(() {
                                  if (controller.isControllerClosed) {
                                    return const SizedBox(width: 10);
                                  }
                                  final isHeld = controller.holdStockSymbols
                                      .contains(
                                        widget.stockCode.symbol.replaceAll(
                                          '.',
                                          '',
                                        ),
                                      );
                                  return isHeld
                                      ? Padding(
                                        padding: EdgeInsets.only(right: 4.0),
                                        child: Icon(
                                          Icons.account_balance_wallet,
                                          color: Colors.blue,
                                          size: 16,
                                        ),
                                      )
                                      : SizedBox(width: 18); // 占位空间保持对齐
                                }),
                              ],
                            ),
                            const SizedBox(height: 4),
                            // 上市时间
                            if (widget.stockCode.listingDate != null)
                              Text(
                                '上市: ${widget.stockCode.listingDate!.toString().substring(0, 10)}',
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey,
                                ),
                              ),
                          ],
                        ),
                      ),

                      // 右侧价格区域 - 使用Obx监听stockData的变化
                      Obx(() {
                        if (controller.isControllerClosed) {
                          return const SizedBox();
                        }

                        final stockModel =
                            controller.stockData[widget.stockCode.symbol];
                        return stockModel != null && stockModel.currentPrice > 0
                            ? Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  stockModel.currentPrice.toStringAsFixed(2),
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                    color: _getPriceColor(
                                      stockModel.changePercent,
                                    ),
                                  ),
                                ),
                                Text(
                                  '${stockModel.changePercent.toStringAsFixed(2)}%',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: _getPriceColor(
                                      stockModel.changePercent,
                                    ),
                                  ),
                                ),
                                if (stockModel.currentPrice == 0)
                                  const Text(
                                    '数据异常',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.orange,
                                    ),
                                  ),
                              ],
                            )
                            : const CircularProgressIndicator();
                      }),
                    ],
                  ),
                  const SizedBox(height: 8),

                  // 近期收盘价（一行显示6天）
                  Obx(() {
                    if (controller.isControllerClosed) {
                      return const SizedBox();
                    }

                    final recentPrices = controller.getRecentPrices(
                      widget.stockCode.symbol,
                    );

                    if (_isLoadingRecentPrices ||
                        (controller.isLoadingRecentPrices.value &&
                            recentPrices.isEmpty)) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '近期收盘:',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Row(
                            children: [
                              const SizedBox(
                                width: 12,
                                height: 12,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                ),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '加载中...${_retryCount > 0 ? '(${_retryCount + 1}/$_maxRetries)' : ''}',
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ],
                      );
                    }

                    if (recentPrices.isEmpty) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '近期收盘:',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          GestureDetector(
                            onTap: _manualLoadRecentPrices,
                            child: Text(
                              '点击加载近期收盘价${_retryCount > 0 ? ' (已尝试$_retryCount次)' : ''}',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.blue,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                          ),
                        ],
                      );
                    }

                    // 取最近6条记录
                    final displayPrices =
                        recentPrices.length > 6
                            ? recentPrices.sublist(0, 6)
                            : recentPrices;

                    // 计算四天前收盘价与当前价格的涨跌幅
                    final fourDayChangePercent =
                        _calculateFourDayChangePercent();

                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              '近期收盘:',
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Text(
                              '近期涨跌幅: ${fourDayChangePercent.toStringAsFixed(2)}%',
                              style: TextStyle(
                                fontSize: 12,
                                color: _getPriceColor(fourDayChangePercent),
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 4),
                        // 一行显示6天收盘价，从左到右是今天、昨天、前天...
                        Row(
                          children: [
                            for (int i = 0; i < displayPrices.length; i++)
                              _buildPriceItem(displayPrices, i),
                          ],
                        ),
                      ],
                    );
                  }),
                ],
              ),
            ),

            // 折叠控件 - 财务指标 - 直接控制标题区域高度
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[100],
                border: Border(
                  top: BorderSide(color: Colors.grey[300]!, width: 1.0),
                ),
              ),
              child: Column(
                children: [
                  // 标题区域
                  SizedBox(
                    height: 35, // 设置标题区域高度
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () async {
                          if (controller.isControllerClosed) return;

                          setState(() {
                            _isExpanded = !_isExpanded;
                          });

                          // 当展开时，重新加载财务指标数据
                          if (_isExpanded) {
                            setState(() {
                              _isLoadingIndicators = true;
                            });

                            try {
                              // 强制重新加载财务指标数据
                              await controller.fetchMainIndicators(
                                widget.stockCode.symbol,
                                force: true,
                              );

                              // 手动触发界面更新
                              if (mounted && !controller.isControllerClosed) {
                                setState(() {});
                              }
                            } catch (e) {
                              print('重新加载财务指标数据失败: $e');
                            } finally {
                              if (mounted && !controller.isControllerClosed) {
                                setState(() {
                                  _isLoadingIndicators = false;
                                });
                              }
                            }
                          }
                        },
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          child: Row(
                            children: [
                              const Text(
                                '财务指标',
                                style: TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  height: 1.0,
                                ),
                              ),
                              if (_isLoadingIndicators)
                                Padding(
                                  padding: const EdgeInsets.only(left: 8.0),
                                  child: SizedBox(
                                    width: 12,
                                    height: 12,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 1,
                                    ),
                                  ),
                                ),
                              const Spacer(),
                              Icon(
                                _isExpanded
                                    ? Icons.expand_less
                                    : Icons.expand_more,
                                size: 16,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),

                  // 内容区域
                  if (_isExpanded) _buildFinancialIndicators(controller),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建财务指标内容
  Widget _buildFinancialIndicators(StockListController controller) {
    if (controller.isControllerClosed) {
      return const SizedBox();
    }

    final indicators = controller.getMainIndicators(widget.stockCode.symbol);

    if (_isLoadingIndicators) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(
            '加载财务数据中...',
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ),
      );
    }

    if (indicators.isEmpty) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(
            '暂无财务数据',
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),
        ),
      );
    }

    // 获取所有类型的数据
    final oneData = indicators['one'] as List<dynamic>? ?? [];
    final middleData = indicators['middle'] as List<dynamic>? ?? [];
    final threeData = indicators['three'] as List<dynamic>? ?? [];
    final yearData = indicators['year'] as List<dynamic>? ?? [];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 年度数据
        if (yearData.isNotEmpty) _buildDataSection('年度数据', yearData),

        // 第三季度数据
        if (threeData.isNotEmpty) _buildDataSection('第三季度数据', threeData),

        // 年中数据
        if (middleData.isNotEmpty) _buildDataSection('年中数据', middleData),

        // 第一季度数据
        if (oneData.isNotEmpty) _buildDataSection('第一季度数据', oneData),
      ],
    );
  }

  Color _getPriceColor(double changePercent) {
    if (changePercent > 0) return Colors.red;
    if (changePercent < 0) return Colors.green;
    return Colors.grey;
  }

  // 构建价格项（显示单日收盘价）
  Widget _buildPriceItem(List<RecentClosingPrice> prices, int index) {
    // 如果是第一天（今天），与第二天的价格比较
    if (index == 0) {
      // 确保有第二天的数据
      if (prices.length > 1) {
        final bool isRising = prices[0].close > prices[1].close;
        return Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Text(
            prices[0].close.toStringAsFixed(2),
            style: TextStyle(
              fontSize: 11,
              color: isRising ? Colors.red : Colors.green,
              fontWeight: FontWeight.bold,
            ),
          ),
        );
      } else {
        // 只有一天数据，不显示颜色变化
        return Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Text(
            prices[0].close.toStringAsFixed(2),
            style: const TextStyle(fontSize: 11),
          ),
        );
      }
    }

    // 对于其他天数，与后一天的价格比较
    if (index < prices.length - 1) {
      final bool isRising = prices[index].close > prices[index + 1].close;
      return Padding(
        padding: const EdgeInsets.only(right: 8.0),
        child: Text(
          prices[index].close.toStringAsFixed(2),
          style: TextStyle(
            fontSize: 11,
            color: isRising ? Colors.red : Colors.green,
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    } else {
      // 最后一天（最早的一天），没有后一天数据，不显示颜色变化
      return Padding(
        padding: const EdgeInsets.only(right: 8.0),
        child: Text(
          prices[index].close.toStringAsFixed(2),
          style: const TextStyle(fontSize: 11),
        ),
      );
    }
  }

  // 构建数据部分（参照CnInfoView格式）
  Widget _buildDataSection(String title, List<dynamic> data) {
    // 按报告日期排序，最新的在前
    data.sort(
      (a, b) => (b['ENDDATE']?.toString() ?? '').compareTo(
        a['ENDDATE']?.toString() ?? '',
      ),
    );

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              columnSpacing: 12,
              columns: const [
                DataColumn(label: Text('报告日期', style: TextStyle(fontSize: 12))),
                DataColumn(
                  label: Text('每股收益', style: TextStyle(fontSize: 12)),
                  numeric: true,
                ),
                DataColumn(
                  label: Text('每股净资产', style: TextStyle(fontSize: 12)),
                  numeric: true,
                ),
                DataColumn(
                  label: Text('净利增长率', style: TextStyle(fontSize: 12)),
                  numeric: true,
                ),
                DataColumn(
                  label: Text('资本公积金', style: TextStyle(fontSize: 12)),
                  numeric: true,
                ),
              ],
              rows:
                  data.map((item) {
                    return DataRow(
                      cells: [
                        DataCell(
                          Text(
                            item['ENDDATE']?.toString() ?? '',
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                        DataCell(
                          Text(
                            _formatNumber(item['F004N']),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                        DataCell(
                          Text(
                            _formatNumber(item['F008N']),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                        DataCell(
                          Text(
                            _formatNumber(item['F053N']),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                        DataCell(
                          Text(
                            _formatNumber(item['F010N']),
                            style: const TextStyle(fontSize: 11),
                          ),
                        ),
                      ],
                    );
                  }).toList(),
            ),
          ),
          const SizedBox(height: 12),
        ],
      ),
    );
  }
}

// 格式化数字
String _formatNumber(dynamic value) {
  if (value == null) return '0.00';

  try {
    if (value is String) {
      return double.parse(value).toStringAsFixed(2);
    } else if (value is int || value is double) {
      return value.toDouble().toStringAsFixed(2);
    }
    return '0.00';
  } catch (e) {
    return '0.00';
  }
}
